﻿

using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using HslCommunication;
using HslCommunication.Profinet.Siemens;
using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media;

using ZedGraph;

namespace CastingWellEquipmentGUI.View.Pages
{
    /// <summary>
    /// TrendChartPage.xaml 的交互逻辑
    /// </summary>
    public partial class TrendChartPage : Page
    {
        public static TrendChartPage instance;

        public static TrendChartPage Instance
        {
            get
            {
                if (instance == null)
                {
                    Console.WriteLine("new Page1.................");
                    instance = new TrendChartPage();
                }
                return instance;
            }
        }
        /// <summary>
        /// 本页面所有标签
        /// </summary>
        private ObservableCollection<Model.Control> controls = new ObservableCollection<Model.Control>();





        public TrendChartPage()
        {
            InitializeComponent();
            controls = XyhUtils.PermissionControl(this, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);

            for (int i = 0; i < controls.Count; i++)
            {

            }

            zgc.MouseDownEvent -= zgc_MouseDownEvent;           //鼠标放下事件
            zgc.MouseDownEvent += zgc_MouseDownEvent;           //鼠标放下事件
            zgc.MouseUpEvent -= zgc_MouseUpEvent;               //鼠标拿起事件
            zgc.MouseUpEvent += zgc_MouseUpEvent;               //鼠标拿起事件
            zgc.MouseMoveEvent -= zgc_MouseMoveEvent;           //鼠标移动事件
            zgc.MouseMoveEvent += zgc_MouseMoveEvent;           //鼠标移动事件

        }

        private void WindowsFormsHost_Loaded(object sender, RoutedEventArgs e)
        {
            CreateGraph_jingzhi(zgc);
            Init_Timer();
            Timer1.Start();
            zgc.AxisChange();//刷新界面
        }
        private Random ran = new Random();
        private PointPairList list = new PointPairList();
        private void CreateGraph_jingzhi(ZedGraphControl zg1)
        {
            #region 现实特征设置
            // get a reference to the GraphPane
            GraphPane myPane = zg1.GraphPane;

            // Change the color of the title
            myPane.Title.FontSpec.FontColor = System.Drawing.Color.Green;

            // Add gridlines to the plot, and make them gray
            myPane.XAxis.MajorGrid.IsVisible = true;
            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.XAxis.MajorGrid.Color = System.Drawing.Color.LightGray;
            myPane.YAxis.MajorGrid.Color = System.Drawing.Color.LightGray;

            myPane.XAxis.Scale.Format = "yyyy-MM-dd HH:mm:ss";   //DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") 

            myPane.XAxis.Scale.FontSpec.Angle = 90;
            //myPane.XAxis.Scale.FontSpec.Size = 14;  //字号 ,最好不要设置
            //myPane.XAxis.Scale.FontSpec.IsBold = true;
            myPane.XAxis.Scale.FontSpec.Border.Style = System.Drawing.Drawing2D.DashStyle.Solid;

            // Move the legend location
            myPane.Legend.Position = ZedGraph.LegendPos.Bottom;

            // Make both curves thicker
            //myCurve.Line.Width = 2.0F;
            //myCurve2.Line.Width = 2.0F;

            #endregion

            LineItem myCurve;

            zg1.GraphPane.Title.Text = "动态折线图";
            zg1.GraphPane.XAxis.Title.Text = "时间";
            zg1.GraphPane.YAxis.Title.Text = "数量";
            zg1.GraphPane.XAxis.Type = ZedGraph.AxisType.DateAsOrdinal;


            //zg1.GraphPane.XAxis.MajorTic.PenWidth = 8.0F;


            for (int i = 0; i <= 100; i++)
            {
                double x = (double)new XDate(DateTime.Now.AddSeconds(-(100 - i)));
                double y = ran.NextDouble();
                list.Add(x, y);
            }
            DateTime dt = DateTime.Now;

            myCurve = zg1.GraphPane.AddCurve("My Curve", list, System.Drawing.Color.DarkGreen, SymbolType.None);

            zg1.AxisChange();
            zg1.Refresh();

        }

        private Timer Timer1 = new Timer();
        private void Init_Timer()
        {
            Timer1.Interval = 1000;
            Timer1.Tick += new EventHandler(Timer1_Tick);

        }


        private void Timer1_Tick(object sender, EventArgs e)
        {
            this.zgc.GraphPane.XAxis.Scale.MaxAuto = true;
            double x = (double)new XDate(DateTime.Now);
            double y = ran.NextDouble();
            list.Add(x, y);
            this.zgc.AxisChange();
            this.zgc.Refresh();


            if (list.Count >= 100)
            {
                list.RemoveAt(0);
            }

        }

        //private static string GetValue(TagInfo tagInfo)
        //{
        //    string result = "";
        //    SiemensS7Net siemens = new SiemensS7Net(SiemensPLCS.S1500, "192.168.0.31");
        //    // 连接对象
        //    OperateResult connectPlc = siemens.ConnectServer();
        //    if (connectPlc.IsSuccess)
        //    {
        //        OperateResult operateResult = siemens.ReadInt32(tagInfo.Address);
        //        if (operateResult.IsSuccess)
        //        {
        //            result = siemens.ReadInt32(tagInfo.Address).Content.ToString();
        //        }
        //        else
        //        {
        //            result = "标签信息错误";
        //        }
        //    }
        //    else
        //    {
        //        result = "连接PLC失败";
        //    }
        //    siemens.ConnectClose();
        //    return result;

        //}

        bool isDragYAxis = false;
        int startYPosition = 0;
        YAxis dragYAxis = null;
        bool isDragXAxis = false;
        int startXPosition = 0;
        XAxis dragXAxis = null;
        int DxValue = 0;
        int DyValue = 0;
        int UxValue = 0;
        int UyValue = 0;

        private bool zgc_MouseDownEvent(ZedGraphControl sender, MouseEventArgs e)
        {
            //初始化起始坐标点
            float startX = 0;
            //其中Rect：
            //获取或设置包含由轴（x轴、y轴和y2轴）限定的区域的矩形。
            //如果手动设置此值，则IsRectAuto值将自动设置为false。
            //X是获取矩形区域左上角的坐标
            float endX = sender.GraphPane.Chart.Rect.X;
            //如果鼠标落下的位置在此范围内 0到 矩形区域左上角的图标 即鼠标落点在Y轴的区域
            if (e.X > startX && e.X < endX)
            {
                //拖拽Y轴标识改为true
                isDragYAxis = true;
                //开始拖拽时Y的坐标值 = 鼠标的Y坐标
                startYPosition = e.Y;
                //获取Y轴的数量
                int yAxisCount = sender.GraphPane.YAxisList.Count;
                //就是获取Y左边Y轴的区域除以Y轴的数量 就是每个Y轴的单位宽度
                float unit = (endX - startX) / yAxisCount;
                //通过循环获取自己要拖拽哪个Y轴
                for (int i = 0; i < yAxisCount; i++)
                {
                    //如果鼠标所在的X坐标对应Y轴的区域内
                    if (e.X < unit * (i + 1) && e.X > unit * i)
                    {
                        //拖拽的Y轴的索引就是反顺序的索引
                        dragYAxis = sender.GraphPane.YAxisList[yAxisCount - (i + 1)];
                        break;
                    }
                }
            }

            //否则就是拖拽X轴          
            //sender.GraphPane.Chart.Rect.Y 获取左上角的Y坐标 再加上区域高度
            float startY = sender.GraphPane.Chart.Rect.Y + sender.GraphPane.Chart.Rect.Height;
            float endY = sender.GraphPane.Rect.Height;
            if (e.Y > startY && e.Y < endY)
            {
                //将拖拽X轴设置为true
                isDragXAxis = true;
                startXPosition = e.X;
                float unit = (endY - startY);
                dragXAxis = sender.GraphPane.XAxis;
            }

            //鼠标落下时的起点
            if (e.Button == MouseButtons.Left)
            {
                //获取鼠标左键的坐标点
                Point mouseDownLocation = new Point(e.X, e.Y);
                GraphPane myPane = sender.GraphPane;
                //获取点击点的坐标值 
                DxValue = e.X;
                DyValue = e.Y;

            }
            else
            {
                DxValue = 0;
                DyValue = 0;
            }
            return default(bool);
        }

        #region 鼠标拿起事件
        /// <summary>
        /// 鼠标拿起事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private bool zgc_MouseUpEvent(ZedGraphControl sender, MouseEventArgs e)
        {
            isDragYAxis = false;
            isDragXAxis = false;
            // 判断是否拖拽的up点
            if (e.Button == MouseButtons.Left)
            {
                Point mouseDownLocation = new Point(e.X, e.Y);
                GraphPane myPane = sender.GraphPane; //获取点击点的坐标值 
                UxValue = e.X;
                UyValue = e.Y;
            }
            else
            {
                UxValue = 0;
                UyValue = 0;
            }
            return default(bool);
        }

        #endregion

        #region 鼠标移动事件
        /// <summary>
        /// 鼠标移动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private bool zgc_MouseMoveEvent(ZedGraphControl sender, MouseEventArgs e)
        {
            //如果是拖动Y轴
            if (isDragYAxis)
            {
                //速度
                float rate = (e.Y - startYPosition) / sender.GraphPane.Chart.Rect.Height;
                //距离
                float diff = rate * (float)(dragYAxis.Scale.Max - dragYAxis.Scale.Min);
                if (rate >= 0.01)
                {
                    //Y轴的刻度最大值加上距离
                    dragYAxis.Scale.Max += diff;
                    //Y轴刻度的最小值加上距离
                    dragYAxis.Scale.Min += diff;
                    startYPosition = e.Y;
                    //当前的最大最小值
                    PointPair pp = new PointPair(dragYAxis.Scale.Min, dragYAxis.Scale.Max);
                    //刷新曲线图
                    sender.AxisChange();
                    sender.Invalidate();

                }
                else if (rate <= -0.01)
                {
                    dragYAxis.Scale.Max += diff;
                    dragYAxis.Scale.Min += diff;
                    startYPosition = e.Y;
                    //当前的最大最小值
                    PointPair pp = new PointPair(dragYAxis.Scale.Min, dragYAxis.Scale.Max);
                    sender.AxisChange();
                    sender.Invalidate();

                }
            }
            //拖拽X轴
            if (isDragXAxis)
            {
                float rate = (e.X - startXPosition) / sender.GraphPane.Chart.Rect.Width;
                float diff = rate * (float)(dragXAxis.Scale.Max - dragXAxis.Scale.Min);
                if (rate >= 0.01)
                {
                    dragXAxis.Scale.Max -= diff;
                    dragXAxis.Scale.Min -= diff;
                    startXPosition = e.X;

                    //当前的最大最小值
                    PointPair pp = new PointPair(dragXAxis.Scale.Min, dragXAxis.Scale.Max);

                    sender.AxisChange();
                    sender.Invalidate();
                }
                else if (rate <= -0.01)
                {
                    dragXAxis.Scale.Max -= diff;
                    dragXAxis.Scale.Min -= diff;
                    startXPosition = e.X;
                    //当前的最大最小值
                    PointPair pp = new PointPair(dragXAxis.Scale.Min, dragXAxis.Scale.Max);

                    sender.AxisChange();
                    sender.Invalidate();
                }
            }

            //判断是否拖拽的up点
            if (e.Button == MouseButtons.Left)
            {
                Point mouseDownLocation = new Point(e.X, e.Y);
                GraphPane myPane = sender.GraphPane; //获取点击点的坐标值 
                UxValue = e.X;
                UyValue = e.Y;
            }
            else
            {
                UxValue = 0;
                UyValue = 0;
            }
            return default(bool);
        }
 
        #endregion
    }
}
